﻿using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using System.Globalization;
using VatLid;
using System.Text.RegularExpressions;
using System.Collections.Generic;        


namespace VatLid
{
    /// <summary>
    /// The class stores all global variables for the application.
    /// </summary>
    public class Utils
    {
        public static string GetPhoneFromText(string phoneNumber)
        {
            string phoneSyntax = "0123456789";
            if (phoneNumber == "") return "";
            string phone = "";
            for (int i = 0; i < phoneNumber.Length; i++)
                if (phoneSyntax.IndexOf(phoneNumber[i]) != -1)
                    phone += phoneNumber[i];

            if (phone != "" && phone.Length > 8)
            {
                if (phone.StartsWith("0"))
                    phone = phone.Substring(1);
                if (!phone.StartsWith("84"))
                    phone = "84" + phone;
            }
            //if (phone.Length != 10 && phone.Length != 11 && phone.Length != 12) 
            //    return "";
            return phone;
        }
       
        public static string GetSmallImage(string url, string width)
        {
            return "http://images.dailyinfo.vn/img.ashx?url=" + url + "&w=" + width;
        }
        public static DataSet SelectItemByID(string connString, string tableName, string id)
        {
            SqlParameter[] parameters = { 
                new SqlParameter("@Table", SqlDbType.NVarChar),			
				new SqlParameter("@ID", SqlDbType.Int),																																					
			};
            parameters[0].Value = tableName;
            parameters[1].Value = Convert.ToInt32(id);
            DataSet ds;
            ds = VatLid.SqlHelper.ExecuteDataset(connString, CommandType.StoredProcedure, "Select_Item_By_ID", parameters);
            return ds;
        }
        public static string UpdateDate(string connStrSport, DataGrid dgrCommon, string tableName, string fieldName)
        {
            string IDS = "";
            try
            {
                IDS = GetListSelected(dgrCommon);
                SqlParameter[] parameters = 
                    { 
                        new SqlParameter("@TableName", SqlDbType.NVarChar ),//0
                        new SqlParameter("@FieldName", SqlDbType.NVarChar ),//0
                        new SqlParameter("@IDS", SqlDbType.NVarChar ),//0
                    };
                parameters[0].Value = tableName;
                parameters[1].Value = fieldName;
                parameters[2].Value = IDS;
                VatLid.SqlHelper.ExecuteNonQuery(connStrSport, CommandType.StoredProcedure, "update_Date", parameters);
                return "";
            }
            catch (Exception e)
            {
                return "Thực hiện không thành công: " + IDS;
            }
        }
        public static string UpdateStatus(string connStrSport, DataGrid dgrCommon, string sTableName, string sFieldName, int intvalue)
        {
            return UpdateStatus(connStrSport, dgrCommon, sTableName, sFieldName, intvalue, "");
        }

        public static string UpdateStatus(string connStrSport, DataGrid dgrCommon, string sTableName, string sFieldName, int intvalue, string logMessage)
        {
            string sTemp = GetListSelected(dgrCommon);
            if (sTemp != "")
            {
                logMessage = "Update bảng " + sTableName + ":" + sTemp + " sang trạng thái " + intvalue;
                string SQL = "";
                try
                {
                    SQL = "UPDATE " + sTableName + " SET " + sFieldName + " = " + intvalue + " WHERE ID in (" + sTemp + ")";
                    VatLid.DAL.ExecuteQuery(connStrSport, SQL);
                    //if (logMessage != "")
                    //{
                    //    VatLid.DAL.INSERT_USER_LOG(HttpContext.Current.Session["USER"].ToString(), logMessage, sTemp, "OK");
                    //}
                    return "Thực hiện thành công: " + sTemp;
                }
                catch (Exception e)
                {
                    return "Thực hiện không thành công: " + sTemp;
                }
            }
            else
            {
               // VatLid.MessageBox.Show("Bạn phải chọn để thực hiện.");
                return "";
            }
        }

        public static void UpdateStatus(string connStrSport, string sTableName, string sFieldName, int intvalue, string sID)
        {
            string SQL = "";
            try
            {
                SQL = "UPDATE " + sTableName + " SET " + sFieldName + " = " + intvalue + " WHERE ID in (" + sID + ")";
                VatLid.DAL.ExecuteQuery(connStrSport, SQL);
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
            }
        }
        public static string GetListSelected(DataGrid dgrCommon)
        {
            string sTemp = "";
            int i;
            for (i = 0; i < dgrCommon.Items.Count; i++)
            {
                if (((CheckBox)dgrCommon.Items[i].FindControl("chkAllDelete")).Checked == true)
                {
                    if (sTemp != "") { sTemp += ","; }
                    sTemp += dgrCommon.DataKeys[i];
                }
            }
            return sTemp;
        }
        public static void FillListStatus(DropDownList ddlStatus)
        {
            ListItem liShow = new ListItem("--Duyệt--", "2");
            ddlStatus.Items.Add(liShow);
            liShow = new ListItem("--Chờ duyệt--", "1");
            ddlStatus.Items.Add(liShow);
            liShow = new ListItem("--Xóa--", "0");
            ddlStatus.Items.Add(liShow);
            liShow = new ListItem("--Tất cả--", "3");
            ddlStatus.Items.Add(liShow);
        }
        public static bool CheckViewFile()
        {
            if (HttpContext.Current.Session["USER"] != null)
            {
                string FileName = getCurrentFileName(HttpContext.Current.Request);
                string UserGroupID = VatLid.Utils.getGroupId(HttpContext.Current.Session).ToString();
                if (DAL.GetRights(UserGroupID, FileName) == false)
                {
                    //HttpContext.Current.Response.Redirect(VatLid.Variables.sWebRoot + "error_info.aspx?err=21");
                    //return false;
                    return true;
                }
                else
                    return true;
            }
            else
                HttpContext.Current.Response.Redirect(VatLid.Variables.sWebRoot + "logout.aspx");
            return false;
        }
        // get current file name from URL 
        public static String getCurrentFileName(HttpRequest Request)
        {
            string P_I = Request.ServerVariables["PATH_INFO"];
            string[] aPI = P_I.Split('/');
            int iLength = aPI.Length;
            return aPI[iLength - 1];
        }

       

        public static void fetchType(DropDownList ddlType)
        {
            ListItem liType = new ListItem("Bình thường ", "0");
            ddlType.Items.Add(liType);
            liType = new ListItem("Đặc biệt", "1");
            ddlType.Items.Add(liType);
        }
           
        // TODO
        public static int getUserId(HttpSessionState session)
        {
            if ((session["USERID"] == null) || (session["USERID"] == "0"))
                return 0;
            else
            return Convert.ToInt32(session["USERID"]);
        }

        public static string getUser(HttpSessionState session)
        {
            if (session["USER"] == null) 
                return "";
            else
                return session["USER"].ToString();
        }

        // TODO
        public static int getGroupId(HttpSessionState session)
        {
            if (session["USERGROUPID"] == null)
                return 0;
            else
                return Convert.ToInt32(session["USERGROUPID"]);            
        }

        public static System.DateTime getSqlDateTime(string date)
        {

            DateTime myResult = new DateTime();

            string[] myFormat = new string[] { "dd/MM/yyyy", "d/M/yyyy", "d/M/yy" };
            CultureInfo myProvider = CultureInfo.InvariantCulture;
            myProvider = new CultureInfo("fr-FR");

            try
            {
                if (date.IndexOf(" ") > 0)
                {
                    date = date.Substring(0, date.IndexOf(" "));
                }
                myResult = DateTime.ParseExact(date, myFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);

            }
            catch (Exception ex)
            {
                Console.WriteLine("" + ex.ToString());
            }

            return myResult;


        }

        public static System.DateTime getSqlDateTimeLong(string date)
        {

            DateTime myResult = new DateTime();

            string[] myFormat = new string[] { "dd/MM/yyyy hh:mi:ss", "MM/dd/yyyy hh:mi:ss", "M/d/yyyy", "d/M/yyyy" };
            CultureInfo myProvider = CultureInfo.InvariantCulture;
            myProvider = new CultureInfo("fr-FR");

            try
            {
                if (date.IndexOf(" ") > 0)
                {
                    date = date.Substring(0, date.IndexOf(" "));
                }
                myResult = DateTime.ParseExact(date, myFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault);

            }
            catch (Exception ex)
            {
                Console.WriteLine("" + ex.ToString());
            }

            return myResult;


        }


     
        public static string getSqlDate(string date)
        {
            string[] d = date.Split('/');
            return d[2] + "-" + d[1] + "-" + d[0];
        }

        public static bool IsDate(string sdate)
        {
            DateTime dt;
            bool isDate = true;
            try
            {
                dt = DateTime.Parse(sdate);
            }
            catch
            {
                isDate = false;
            }
            return isDate;
        }
        public static string removeSpecialCharacter(string input)
        {
            string result = System.Text.RegularExpressions.Regex.Replace(input, @"[^\w\@\s\.,:%-/]", " ");
            result = result.Replace("&nbsp", "");
            return result;//System.Text.RegularExpressions.Regex.Replace(input, @"[^\w\@\s\.-:,]", " ");
           
        }

        public static string formatStringDate(string date)
        {
            string result = "";
            int leng = date.Length - date.LastIndexOf("/");
            result = date.Substring(date.IndexOf("/") + 1, date.LastIndexOf("/") - date.IndexOf("/"));
            result += date.Substring(0, date.IndexOf("/"));
            result += date.Substring(date.LastIndexOf("/"), leng);


            return result;
        }

        public static string StripDiacritics(string accented)
        {
            string result;
            //return VatLid.DAL.ConvertVietnameseCharacterToEN(accented);
            Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string strFormD = accented.Normalize(System.Text.NormalizationForm.FormD);
            result = regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
            return VatLid.DAL.ConvertVietnameseCharacterToEN(result);

        }
        public static bool isEditable(string groupid, string itemid)
        {
            string SQL = "SELECT * FROM dbo.system_group_function WHERE groupid=" + groupid + " AND itemid=" + itemid + " AND funvalue>= 2 ";
            return isExistRow(SQL);
        }
        public static bool isDeleteable(string groupid, string itemid)
        {
            string SQL = "SELECT * FROM dbo.system_group_function WHERE groupid=" + groupid + " AND itemid=" + itemid + " AND funvalue= 3 ";
            return isExistRow(SQL);
        }
        public static bool isExistRow(string SQL)
        {
            try
            {
                ArrayList al = VatLid.DAL.GetDataReaderToArrayList(SQL);
                if (al.Count != 0)
                    return true;
                else
                    return false;
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
                return false;
            }
        }

        public static bool isAdminGroup(string groupid)
        {                    
            try
            {              
                SqlParameter[] parameters = { 
                new SqlParameter("@groupid", SqlDbType.Int),																																					
                };
                parameters[0].Value = Convert.ToInt32(groupid);
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "system_group_user$SelectByGroupid", parameters);

                if (ds.Tables[0].Rows.Count > 0)
                {
                    string readName = ds.Tables[0].Rows[0]["groupname"].ToString();

                    if (readName == "ADMINISTRATOR")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }                   
                }
                else
                {
                    return false;
                }    
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
                return false;
            }
        }


        public static bool isNews(string itemid)
        {

            string SQL = "SELECT itemId, itemParent FROM system_items WHERE itemParent in(11,78,79) AND itemId=" + itemid;
            try
            {
                ArrayList al = VatLid.DAL.GetDataReaderToArrayList(SQL);
                if (al.Count != 0)
                    return true;
                else
                    return false;
            }
            catch (Exception e)
            {
                VatLid.DAL.ExceptionProcess(e);
                return false;
            }
        }

        public static String CleanInput(string strIn)
        {
            // Replace invalid characters with empty strings.
            string result = Regex.Replace(strIn.Trim(), @"[^\w\.@-]", " ");
            result = Regex.Replace(result, " {2,}", " ");
            return result;
        }

        public static string ReplaceSpace(string strIn)
        {
            return Regex.Replace(strIn, " {2,}", " ");
        }

        public static string ReplaceSpecial(string strIn)
        {
            return Regex.Replace(strIn, " {2,}", " ");
        }
        // lay filter keyword: vi du: SQL += VatLid.Utils.GetKeyWordFilter(ddlSearch.SelectedIndex, txtKeyword.Text, "t1.Name,t1.Description"); 
        public static string GetKeyWordFilter(int index, string keyword, string listField)
        {
            string keywordSearch = CleanInput(keyword);
            // index = index - 1;
            if (keywordSearch.Trim().Length > 0)
            {
                string[] fields = listField.Split(',');
                if (fields.Length < 1)
                    return " ";
                string filter = "";
                switch (index)
                {
                    case 0: // tat ca
                        if (fields.Length == 1)
                            filter = " AND CHARINDEX(N'" + keywordSearch.Trim() + "'," + fields[0] + ")<>0 ";
                        else
                        {
                            filter = " AND (CHARINDEX(N'" + keywordSearch.Trim() + "'," + fields[0] + ")<>0 ";
                            for (int i = 1; i < fields.Length; i++)
                                filter += " OR CHARINDEX(N'" + keywordSearch.Trim() + "'," + fields[i] + ")<>0";
                            filter += ") ";
                        }
                        break;
                    default:
                        filter = " AND CHARINDEX(N'" + keywordSearch.Trim() + "'," + fields[index - 1] + ")<>0 ";
                        break;
                }
                return filter;
            }
            else
                return " ";
        }

        // lay filter keyword: vi du: SQL += VatLid.Utils.GetKeyWordFilter(ddlSearch.SelectedIndex, txtKeyword.Text, "t1.Name,t1.Description"); 
        public static string GetKeyWordOrderBy(int index, string listField, bool status)
        {
            // index = index - 1;
            string statusLable = "";
            if (status == false)
            {
                statusLable = " DESC";
            }
            else
            {
                statusLable = " ASC";
            }
            string[] fields = listField.Split(',');
            if (fields.Length < 1)
                return " ";
            string filter = "";
            switch (index)
            {
                case 0: // tat ca                      
                    filter = " ORDER BY ";
                    for (int i = 0; i < fields.Length; i++)
                        filter += fields[i] + statusLable + ",";
                    filter = filter.Substring(0, filter.Length - 1);
                    break;
                default:
                    filter = " ORDER BY " + fields[index - 1] + statusLable;
                    break;
            }
            return filter;

        }

        public static string GetKeyWordCRM(string keyword, string listField, string relation)
        {
            if ((keyword.Trim().Length > 0) && (listField.Trim().Length > 0))
            {

                string[] fields = listField.Split(',');
                if (fields.Length < 1)
                    return " ";
                string filter = " AND ( ";
                for (int i = 0; i < fields.Length; i++)
                {
                    for (int j = 0; j < searchKeyword(keyword.Trim()).Length - 1; j++)
                    {
                        filter += " CHARINDEX(N'" + searchKeyword(keyword.Trim())[j].ToString().Trim() + "'," + fields[i] + ") <>0 " + relation;
                    }
                    filter += " CHARINDEX(N'" + searchKeyword(keyword.Trim())[searchKeyword(keyword.Trim()).Length - 1].ToString().Trim() + "'," + fields[i] + ") <>0 ";
                    if (i < fields.Length - 1)
                    {
                        filter += ") AND (";
                    }
                    else
                    {
                        filter += ")";
                    }
                }

                return filter;
            }
            else
                return " ";
        }


        public static string GetKeyWordCRM1(string keyword, string listField, string relation)
        {
            if ((keyword.Trim().Length > 0) && (listField.Trim().Length > 0))
            {

                string[] fields = listField.Split(',');
                if (fields.Length < 1)
                    return " ";
                string filter = " AND ( ";
                for (int i = 0; i < fields.Length; i++)
                {
                    for (int j = 0; j < searchKeyword(keyword.Trim()).Length - 1; j++)
                    {
                        filter += " CHARINDEX(N''" + searchKeyword(keyword.Trim())[j].ToString().Trim() + "''," + fields[i] + ") <>0 " + relation;
                    }
                    filter += " CHARINDEX(N''" + searchKeyword(keyword.Trim())[searchKeyword(keyword.Trim()).Length - 1].ToString().Trim() + "''," + fields[i] + ") <>0 ";
                    if (i < fields.Length - 1)
                    {
                        filter += ") AND (";
                    }
                    else
                    {
                        filter += ")";
                    }
                }

                return filter;
            }
            else
                return " ";
        }

        public static string[] searchKeyword(string Keyword)
        {
            string[] words = null;

            if (Keyword != "")
            {
                words = Keyword.Split('+');
            }

            return words;
        }

        //public static string exportExcel(System.Data.DataView dv, string[] header, string timeReport, string[] column, string dict, string filename)
        //{
        //    if (HttpContext.Current.Session["USER"] == null)
        //        HttpContext.Current.Response.Redirect(VatLid.Variables.sWebRoot + "logout.aspx");
        //    CreateExcelDoc export = new CreateExcelDoc();
        //    export.fillData(dict + "\\" + filename + ".xls", dv.Table, header, timeReport, HttpContext.Current.Session["USER"].ToString(), column);

        //    HttpContext.Current.Response.Redirect("~\\doc" + "\\" + filename + ".xls");
        //    return "";

        //}


        public static string getCountInsert(int str, int count)
        {
            string result = "";

            //int k = (str.Length + 1) / 2;
            result = str.ToString() + "/" + (count - 2).ToString();
            return result;
        }

        public static string getCountInsert(string str, int count)
        {
            string result = "";

            int k = (str.Length + 1) / 2;
            result = k.ToString() + "/" + count.ToString();
            return result;
        }
       

        public static void addImageToFile(string id, byte[] imgdata)
        {
            string imdDBLocal = ConfigurationSettings.AppSettings["ImageLead"];
            string filepath = imdDBLocal + id.ToString();
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            FileStream fStream = new FileStream(filepath, FileMode.CreateNew);
            BinaryWriter bw = new BinaryWriter(fStream);
            bw.Write(imgdata);
            bw.Close();
            fStream.Close();
        }


        public static void addImageToFile(string id, byte[] imgdata, string imagePath)
        {
            string imdDBLocal = ConfigurationSettings.AppSettings[imagePath];
            string filepath = imdDBLocal + id.ToString();
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            FileStream fStream = new FileStream(filepath, FileMode.CreateNew);
            BinaryWriter bw = new BinaryWriter(fStream);
            bw.Write(imgdata);
            bw.Close();
            fStream.Close();
        }


        public static ArrayList getModule(string module)
        {
            ArrayList result = new ArrayList();
            string modulevalue = module;

            for (int i = 0; i < module.Length; i++)
            {
                if (module.Substring(i, 1) != ",")
                    result.Add(module.Substring(i, 1));
            }
            return result;
        }

        public static string[] getArrayID(string arrayID)
        {
            string[] result = arrayID.Split(',');
            return result;
        }       

        public static string StripTagsRegex(string source)
        {
            return Regex.Replace(source, "<.*?>", string.Empty);
        }

        /// <summary>
        /// Compiled regular expression for performance.
        /// </summary>
        static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

        /// <summary>
        /// Remove HTML from string with compiled Regex.
        /// </summary>
        public static string StripTagsRegexCompiled(string source)
        {
            return _htmlRegex.Replace(source, string.Empty);
        }

        /// <summary>
        /// Remove HTML tags from string using char array.
        /// </summary>
        public static string StripTagsCharArray(string source)
        {
            char[] array = new char[source.Length];
            int arrayIndex = 0;
            bool inside = false;

            for (int i = 0; i < source.Length; i++)
            {
                char let = source[i];
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (!inside)
                {
                    array[arrayIndex] = let;
                    arrayIndex++;
                }
            }
            return new string(array, 0, arrayIndex);
        }     

        public static string VNFormatDate(DateTime date)
        {
            string sDate = "";
            switch (date.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    sDate = "Thứ hai";
                    break;
                case DayOfWeek.Tuesday:
                    sDate = "Thứ ba";
                    break;
                case DayOfWeek.Wednesday:
                    sDate = "Thứ tư";
                    break;
                case DayOfWeek.Thursday:
                    sDate = "Thứ năm, ";
                    break;
                case DayOfWeek.Friday:
                    sDate = "Thứ sáu";
                    break;
                case DayOfWeek.Saturday:
                    sDate = "Thứ bảy";
                    break;
                case DayOfWeek.Sunday:
                    sDate = "Chủ nhật";
                    break;
            }

            sDate += ", " + date.ToString("dd/MM/yyyy hh:mm tt");
            return sDate;
        }

        public static string relapceLocation(string location)
        {
            return location.Replace("'", "''");
        }


        public static string getListModule(string groupid, string status)
        {
            if (status.Trim().Length < 1)
                return "";

            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(VatLid.DAL.getConnectionString());
                conn.Open();
                string SQL = "SELECT listcategories FROM  system_module_categories WHERE groupid=" + groupid + " AND categories_status = " + status;
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, "list");
                string listproduct = "''";
                if (ds.Tables["list"].Rows.Count > 0)
                    listproduct = ds.Tables["list"].Rows[0]["listcategories"].ToString();
                return listproduct;
            }
            catch
            {
                return "''";
            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
        }

        public static string getMess_Cate(string id)
        {
            string lisProduct = ",";

            try
            {

                SqlParameter[] parameters = { 
            new SqlParameter("@ID", SqlDbType.Int),																																					
        };
                parameters[0].Value = Convert.ToInt32(id);
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Mess_Cate$Select", parameters);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["cid"].ToString() != "0")
                        lisProduct += ds.Tables[0].Rows[i]["cid"].ToString() + ",";
                    else
                        lisProduct += ds.Tables[0].Rows[i]["pid"].ToString() + ",";
                }

                return lisProduct;

            }
            catch (Exception ex)
            {
                return lisProduct;
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static string getMess_Event(string id)
        {
            string lisProduct = ",";

            try
            {

                SqlParameter[] parameters = { 
            new SqlParameter("@ID", SqlDbType.Int),																																					
        };
                parameters[0].Value = Convert.ToInt32(id);
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Mess_Cate$Select", parameters);

                for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
                {
                    lisProduct += ds.Tables[1].Rows[i]["eid"].ToString() + ",";
                }

                return lisProduct;

            }
            catch (Exception ex)
            {
                return lisProduct;
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static string getMess_Person(string id)
        {
            string lisProduct = ",";

            try
            {

                SqlParameter[] parameters = { 
            new SqlParameter("@ID", SqlDbType.Int),																																					
        };
                parameters[0].Value = Convert.ToInt32(id);
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Mess_Cate$Select", parameters);

                for (int i = 0; i < ds.Tables[2].Rows.Count; i++)
                {

                    lisProduct += ds.Tables[2].Rows[i]["pid"].ToString() + ",";
                }

                return lisProduct;

            }
            catch (Exception ex)
            {
                return lisProduct;
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static string getMess_Persion_Cate(string id)
        {
            string lisProduct = ",";

            try
            {

                SqlParameter[] parameters = { 
            new SqlParameter("@ID", SqlDbType.Int),																																					
        };
                parameters[0].Value = Convert.ToInt32(id);
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Mess_Person_Cate$Select", parameters);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {

                    lisProduct += ds.Tables[0].Rows[i]["pe_id"].ToString() + ",";
                }

                return lisProduct;

            }
            catch (Exception ex)
            {
                return lisProduct;
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static string getPersion_Cate(string id)
        {
            string lisProduct = ",";

            try
            {

                SqlParameter[] parameters = { 
            new SqlParameter("@ID", SqlDbType.Int),																																					
        };
                parameters[0].Value = Convert.ToInt32(id);
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Pesion_Cate$Select", parameters);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                 
                        lisProduct += ds.Tables[0].Rows[i]["cid"].ToString() + ",";
                }

                return lisProduct;

            }
            catch (Exception ex)
            {
                return lisProduct;
               
            }
        }

        public static string getMess_MediaSrc(string mid, string type)
        {
            string Src = "";

            try
            {

                SqlParameter[] parameters = { 
                    new SqlParameter("@mid", SqlDbType.Int),																																					
                    new SqlParameter("@type", SqlDbType.Int),																																					

            };
                parameters[0].Value = Convert.ToInt32(mid);
                parameters[1].Value = Convert.ToInt32(type);
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_Mess_Media$SelectByMid", parameters);

                 if(ds.Tables[0].Rows.Count > 0) 
                {

                    Src = ds.Tables[0].Rows[0]["src"].ToString();
                }

                return Src;

            }
            catch (Exception ex)
            {
                return Src;
                VatLid.DAL.ExceptionProcess(ex);
            }
        }

        public static string getFunvalue(string itemId, string groupid)
        {
            string Funvalue = "1";

            try
            {

                SqlParameter[] parameters = { 
                    new SqlParameter("@itemId", SqlDbType.Int),																																					
                    new SqlParameter("@groupid", SqlDbType.Int),																																					

            };
                parameters[0].Value = Convert.ToInt32(itemId);
                parameters[1].Value = Convert.ToInt32(groupid);
                DataSet ds;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "cms_system_group_function$SelectByID", parameters);

                if (ds.Tables[0].Rows.Count > 0)
                {

                    Funvalue =  ds.Tables[0].Rows[0]["funvalue"].ToString();
                }

                return Funvalue;

            }
            catch (Exception ex)
            {
                return Funvalue;
                VatLid.DAL.ExceptionProcess(ex);
            }
        }


        public static string GetList( string groupid, string status)
        {
            DataSet ds = new DataSet();
            SqlConnection conn = null;
            try
            {
                conn = new SqlConnection(SecureConnection.GetCnxString("ConnStr"));
                string SQL = "SELECT listcategories FROM  system_module_categories WHERE groupid=" + groupid + " AND categories_status = " + status;
                SqlDataAdapter da = new SqlDataAdapter(SQL, conn);
                da.Fill(ds, "list");
                string listproduct = "''";
                if (ds.Tables["list"].Rows.Count > 0)
                    listproduct = ds.Tables["list"].Rows[0]["listcategories"].ToString();
                return listproduct;
            }
            catch
            {
                return "''";
            }
        }


        public static bool isComment(object id)
        {          
            try
            {
                SqlParameter[] parameters = 
                    { 
	                    new SqlParameter("@mid", SqlDbType.Int),		
                        new SqlParameter("@Type", SqlDbType.Int)		
	                };

                int _id = Int32.Parse(id.ToString());
               

                parameters[0].Value = _id;
                parameters[1].Value = 1;

                DataSet dt = VatLid.SqlHelper.ExecuteDataset(DAL.getConnectionString(), CommandType.StoredProcedure, "cms_AdminComments$Select", parameters);

                if (dt.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }                
            }
            catch
            {
                return false;
            }
        }

        public static string getType_Date(string txtDate)
        {
            string sDate = txtDate.Trim().Replace("/", "");
            return sDate;
        }


        public static bool checkImageType(HtmlInputFile fileImage, Label lblError)
        {
            bool result = false;
            int intContentLength = Convert.ToInt32(ConfigurationSettings.AppSettings["ContentLength"]);

            if ((fileImage.PostedFile != null) && (fileImage.PostedFile.ContentLength != 0))
            {                
                if (fileImage.PostedFile.ContentType != "image/gif" && fileImage.PostedFile.ContentType != "image/jpg" && fileImage.PostedFile.ContentType != "image/pjpeg" && fileImage.PostedFile.ContentType != "image/jpeg")
                {

                    lblError.Text = "Không upload được loại file \"" + fileImage.PostedFile.ContentType + "\". Chỉ upload loại file .jpg, .gif or .png.";
                    result = true;
                }
                if (fileImage.PostedFile.ContentLength > intContentLength)
                {
                    lblError.Text = "File upload không quá maxsize 10Mb";
                    result = true;
                }
            }

            return result;

        }


        public static string getPathFileName(HtmlInputFile fileImage, string Thang, string Ngay, List<string> list_images, string IDImageRandom, string mumber)
        {
            string pathResult = "";

            string path1 = @"archive/imageslead/";
            string fileimages = getFileImages(fileImage, IDImageRandom, mumber);

            if (fileimages.Length > 1)
            {
                pathResult = path1 + Thang + "/" + Ngay + "/" + fileimages;
                list_images.Add(@"http://images.dailyinfo.vn/" + pathResult);
            }
            else
            {
                pathResult = path1 + Thang + "/" + Ngay + "/" + "template.jpg";

            }        

            return pathResult;

        }

        public static string getPathFileNameHome(HtmlInputFile fileImage, string Thang, string Ngay, List<string> list_images, string id,string IDImageRandom,string mumber)
        {
            string pathResult = "";

            string path1 = @"archive/imageslead/";
            string fileimages = getFileImages(fileImage, IDImageRandom, mumber);

            if (fileimages.Length > 1)
            {
                pathResult = path1 + Thang + "/" + Ngay + "/" + fileimages;
                list_images.Add(@"http://images.dailyinfo.vn/" + pathResult);

                
            }
            else
            {
                string cSQL = "SELECT LeadImage as ID FROM Messages WHERE  ID=" + id;
                ArrayList al = VatLid.DAL.GetDataReaderToArrayList(cSQL);
                string[][] arrReturn = (string[][])al.ToArray(typeof(string[]));
                if (al.Count > 0)
                {
                    pathResult = arrReturn[0][0].Trim();
                }

            }

            return pathResult;

        }


        public static string getPathFileNameVideo(HtmlInputFile fileImage, string Thang, string Ngay, List<string> list_images, string IDImageRandom, string mumber)
        {
            string pathResult = "";
            string path2 = @"archive/media/";


            //string path1 = @"archive/imageslead/";
            string fileimages = getFileVideo(fileImage, IDImageRandom, mumber);

            if (fileimages.Length > 1)
            {
                pathResult = path2 + Thang + "/" + Ngay + "/" + fileimages;
                list_images.Add(@"http://images.dailyinfo.vn/" + pathResult);
            }
            else
            {
                pathResult = path2 + Thang + "/" + Ngay + "/" + "template.jpg";

            }

            return pathResult;

        }

        public static string getFileImages(HtmlInputFile fileImage, string IDImageRandom, string mumber)
        {
            string fileImages = "";

         
            string filename = fileImage.PostedFile.FileName;

            int pos = filename.LastIndexOfAny(new char[] { '/', '\\' });
            if (pos >= 0) filename = filename.Substring(pos + 1);
        
            if ((fileImage.PostedFile != null) && (fileImage.PostedFile.ContentLength != 0))
            {
                fileImages = "thumb" + mumber +"_"+ IDImageRandom + filename.Substring(filename.LastIndexOf("."));               
            }
           
            return fileImages;

        }



        public static string getFileVideo(HtmlInputFile fileImage, string IDImageRandom, string mumber)
        {
            string fileImages = "";
           
            string filename = fileImage.PostedFile.FileName;

            int pos = filename.LastIndexOfAny(new char[] { '/', '\\' });
            if (pos >= 0) filename = filename.Substring(pos + 1);

            if ((fileImage.PostedFile != null) && (fileImage.PostedFile.ContentLength != 0))
            {
                fileImages = mumber + "_" + IDImageRandom + filename.Substring(filename.LastIndexOf("."));                

            }
            return fileImages;

        }

        public static byte[] getByteFile(HtmlInputFile fileImage)
        {
            byte[] result = null;

            result = new byte[fileImage.PostedFile.ContentLength];
            fileImage.PostedFile.InputStream.Read(result, 0, fileImage.PostedFile.ContentLength);

            return result;

        }

      
        private static string getMobile(string User, string pass)
        {
            string mobile = "";
            try
            {
                SqlParameter[] parameters = { 
                new SqlParameter("@UserName", SqlDbType.NVarChar),	
			    new SqlParameter("@Password", SqlDbType.NVarChar),	    	        
                
                };
                parameters[0].Value = User.Trim().Replace("'", "''");
                parameters[1].Value = SaltedHash.EncodeMD5(pass.Replace("'", "''"));

                DataSet ds = null;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "system_user_info$SelectUserLogin", parameters);

                DataTable dt = new DataTable();
                dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    mobile = dt.Rows[0]["phone"].ToString();
                }
            }
            catch (Exception ex)
            {
                mobile = "";
            }
            return mobile;
        }


        private static string getPassMobile(string Mobile)
        {
            string passMobile = "";
            try
            {
                SqlParameter[] parameters = { 
                new SqlParameter("@Mobile", SqlDbType.NVarChar),	
			     	        
                
                };
                parameters[0].Value = Mobile;
               
                DataSet ds = null;
                ds = VatLid.SqlHelper.ExecuteDataset(VatLid.DAL.getConnectionString(), CommandType.StoredProcedure, "System_GetEnPass$Select", parameters);

                DataTable dt = new DataTable();
                dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    passMobile = dt.Rows[0]["pas"].ToString();
                }
                else
                {
                    passMobile = "2";
                }
            }
            catch (Exception ex)
            {
                passMobile = "2";
            }
            return passMobile;
        }


       
    }
}
